package drds.global_transaction.lock;

import drds.common.Author;
import drds.global_transaction.Authors;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
    插入共享锁如果之前
    未锁：初始一把共享锁
    已有互斥锁：获取锁失败
    已有共享锁：共享队列+1，获取锁成功
 */
@Author(name = Authors.LI_YANG)
public class ShareILock extends Lock
{
    @Override
    public void lock() throws SQLException
    {
        Connection connection = null;
        String sql = "select count(0) as total from  global_transaction_lock where  table_name = ? and primary_key_column_value =? and exclusive_lock=?";//
        ResultSet resultSet = drds.dbutils.native_sql.Db.query(connection, sql, new Object[]{tableName, primaryKeyColumnValue, exclusiveLock});
        resultSet.next();
        int total = resultSet.getInt("total");
        if (total == 0)
        {
            insertLock();
            insertShareLock();
        } else if (total == 1)
        {
            throw new SQLException();
        } else
        {
            insertShareLock();
        }

        setLock(Boolean.TRUE);

    }

    @Override
    public void unlock() throws SQLException
    {
        deleteLock();
        setLock(Boolean.FALSE);
    }

    private void insertShareLock() throws SQLException
    {
        Connection connection = null;
        String sql = "insert into global_transaction_lock (table_name,primary_key_column_value,global_transaction_id,branch_transaction_id,exclusiveLock,shareLock,create_time)values(?,?,?,?,?,?)";//
        drds.dbutils.native_sql.Db.update(connection, sql,
                new Object[]{tableName,//
                        primaryKeyColumnValue,//
                        globalTransactionId,//
                        branchTransactionId,//
                        globalTransactionId,//
                        shareLock,//
                        createDateTimeLong//
                });
    }
}
